package map;

import java.util.*;
import java.util.function.BiConsumer;

/*
给出一个字符串,统计每一个字符出现的次数,按顺序输出
 */
public class MapTest {
    public static void main(String[] args) {
        /*
          思路:键值对应,使用map,有排序,选用TreeMap
              1.创建TreeMap集合
              2.将字符串拆分为字符数组
              3遍历数组,如果数据不存在,使用put()将他存入集合
              4存在,依旧使用put()方法,将他的值+1并覆盖
         */
        String str="afscsg3ssa";
        myMethod(str);

    }

    private static void reCodeMethod(String str) {
        //拆分字符串,得到每一个字符
        char[] chars = str.toCharArray();
        TreeMap<Character,Integer>treeMap=new TreeMap();
        for (int i = 0; i <chars.length ; i++) {
            if(!treeMap.containsKey(chars[i])){
                //判断字符是否已经存在,若不存在,将他存入
                treeMap.put(chars[i],1);
            }else {
                //存在,修改他,让他key+1
                treeMap.put(chars[i], 1+treeMap.get(chars[i]));
            }
        }
        StringBuilder stringBuilder=new StringBuilder();
        treeMap.forEach(new BiConsumer<Character, Integer>() {
            @Override
            public void accept(Character character, Integer integer) {
                stringBuilder.append(character+"("+integer+")");
            }
        });
        System.out.println(stringBuilder);
    }
    //自己方法,思路有问题,虽然解决了,但是把问题复杂化
    private static void myMethod(String str) {
        char[] charStr = str.toCharArray();
        Set<Character> keyStr=new TreeSet<>();
        int max=0;
        for (int i = 0; i <charStr.length ; i++) {
            keyStr.add(charStr[i]);
        }
        HashMap<Character,Integer> hashMapMap=new HashMap<>();
        for (Character chars:keyStr){
            int count=0;
            for (int i = 0; i <charStr.length ; i++) {
                if (chars.equals(charStr[i])){
                    count++;
                    hashMapMap.put(chars,count);
                }
            }
        }
        System.out.println(hashMapMap);
        Set<Map.Entry<Character, Integer>> entries = hashMapMap.entrySet();
        for (Map.Entry<Character, Integer>entry1:entries){
            if (entry1.getValue()>max){
                max=entry1.getValue();
            }
        }
        Set<Character> characters = hashMapMap.keySet();
        for (Character character:characters){
            if ( hashMapMap.get(character)==max){
                System.out.println(character+"---"+hashMapMap.get(character));
            }

        }


    }
}
